import { requestApi } from '#/api';
import { getRulesForEditOption } from '#/utils';
import { cloneDeep } from '@vben/utils';
import { nextTick, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';

// 定义参数类型
type editOption = {
  [key: string]: any;
};

export default function useEditHooks(
  editOption: editOption,
  emit: (event: string, ...args: any[]) => void,
) {
  const formRef = ref(); // form event
  const gather = reactive({
    visible: false,
    loading: false,
    title: '',
    rules: {},
  }); // 编辑页集合配置

  // 获取表单限制
  function getRules(): void {
    if (editOption.editStatus) {
      gather.rules = getRulesForEditOption(editOption);
    } else {
      gather.rules = {};
    }
  }
  // 关闭侧边栏
  function close() {
    gather.visible = false;
    formRef.value.resetFields();
    editOption.data = {
      ...editOption.dataModel,
      id: null,
    };
  }
  // 获取详情
  async function getDetail(payload: any) {
    let para;
    if (editOption.apiType === 1) {
      //table 模式
      para = cloneDeep(editOption.tableApi);
      para.searchInfo = JSON.stringify({
        [editOption.tableApi.key]: { value: payload, method: '=' },
      }); //对象转字符串
    } else {
      para = { id: payload };
    }
    const { data } = await requestApi(
      editOption.api.detail.url,
      para,
      editOption.api.detail.method,
    );
    editOption.data = data;
  }
  // 添加编辑详情页进入数据修改
  async function showEdit(data: any, option: any) {
    switch (option) {
      case 'add':
        editOption.title = '新建';
        editOption.editStatus = true;
        editOption.isEdit = false;
        editOption.editType = option;
        editOption.data = editOption.dataModel; // 新
        if (formRef.value) formRef.value.resetFields();
        break;
      case 'edit':
        editOption.title = '编辑';
        editOption.editStatus = true;
        editOption.isEdit = true;
        editOption.editType = option;
        await nextTick(() => {
          editOption.data.id = data.id;
          getDetail(data.id);
        });
        break;
      default:
        editOption.title = '详情';
        editOption.editStatus = false;
        editOption.editType = '';
        await nextTick(() => {
          editOption.data.id = data.id;
          getDetail(data.id);
        });
        break;
    }
    gather.visible = true;
  }
  function submit() {
    getRules();
    gather.loading = true;
    formRef.value.validate(async (valid: any) => {
      if (valid) {
        let params;
        if (editOption.apiType === 1) {
          //table 模式
          params = {
            tableName: editOption.tableApi.tableName,
            dataInfo: cloneDeep(editOption.data),
            searchInfo: JSON.stringify({}),
          };
          //处理数据值 字符串 单引号问题
          for (const key in params.dataInfo) {
            params.dataInfo[key] = "'" + params.dataInfo[key] + "'";
          }
          //移除自增主键
          const pKey = editOption.tableApi.key || 'id';
          delete params.dataInfo[pKey];
          params.dataInfo = JSON.stringify(params.dataInfo);

          if (editOption.editType === 'edit') {
            params.searchInfo = JSON.stringify({
              [pKey]: { value: editOption.data.id, method: '=' },
            });
          }
        } else {
          params = { ...editOption.data };
        }

        if (editOption.editType === 'add') {
          const res = await requestApi(
            editOption.api.add.url,
            params,
            editOption.api.add.method,
          );
          if (res.code === 2000) {
            close();
            ElMessage.success('新建成功');
            emit('fetchData');
            // 清空对象数据
            for (const key in editOption.data) {
              editOption.data[key] = editOption.dataModel[key] || '';
            }
          }
        } else if (editOption.editType === 'edit') {
          const res = await requestApi(
            editOption.api.update.url,
            params,
            editOption.api.update.method,
          );
          if (res.code === 2000) {
            close();
            ElMessage.success('编辑成功');
            emit('fetchData');
            // 清空对象数据
            for (const key in editOption.data) {
              editOption.data[key] = editOption.dataModel[key] || '';
            }
          }
        }
        gather.loading = false;
      } else {
        gather.loading = false;
      }
    });
  }
  return {
    formRef,
    gather,
    close,
    getDetail,
    showEdit,
    submit,
    getRules,
  };
}
